package com.itheima.tanhua.member.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.tanhua.base.DTO.LoginDTO;
import com.itheima.tanhua.base.VO.TokenVo;
import com.itheima.tanhua.base.common.BaseContext;
import com.itheima.tanhua.base.common.Result;
import com.itheima.tanhua.base.entity.ThMembers;
import com.itheima.tanhua.member.mapper.ThMembersMapper;
import com.itheima.tanhua.member.service.ThMembersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author yangjiahao
 * @since 2023-01-30
 */
@Slf4j
@Service
public class ThMembersServiceImpl extends ServiceImpl<ThMembersMapper, ThMembers> implements ThMembersService {

    @Autowired
    private RedisTemplate redisTemplate;

    String key = "1234";

    @Override
    public void sendMessage(String phone) {
        String sendCountKey = "tanhua:member:sms:"+phone+":count";
        String key = "tanhua:member:sms:" + phone;

        //判断这个场景下累计发送了计次短信
        int count = 0;

        if (redisTemplate.hasKey(sendCountKey)){
            count = Integer.parseInt(redisTemplate.opsForValue().get(sendCountKey) + "");
        }

        if (count>10){
            //报错
            throw new RuntimeException("当天短信发送过多");
        }

        //发送短信
        String code = RandomUtil.randomNumbers(6);
        //存入redis
        redisTemplate.opsForValue().set(key,code,90,TimeUnit.SECONDS);
        //更新统计次数
        redisTemplate.opsForValue().set(key,count+1,1,TimeUnit.DAYS);
        log.info("短信发送逻辑完成");
    }

    @Override
    public Result login(LoginDTO loginDTO) {
        //验证验证码
        String code = loginDTO.getCode();
        String redisCode = (String) redisTemplate.opsForValue().get("sendMessage" + loginDTO.getPhone());
        if (!code.equals(redisCode)){
            return Result.error("验证码错误");
        }
        //查询手机号是否存在
        LambdaQueryWrapper<ThMembers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ThMembers::getPhone,loginDTO.getPhone());
        ThMembers member = getOne(wrapper);

        //不存在，保存并签发token
        if (ObjectUtil.isEmpty(member)){
            ThMembers thMembers = new ThMembers();
            thMembers.setPhone(loginDTO.getPhone());
            save(thMembers);
            ThMembers saveMember = getOne(wrapper);

            //存入Tl
            BaseContext.setCurrentId(saveMember.getId());

            String token = token(saveMember.getId());
            redisTemplate.opsForValue().set(token,token,3600,TimeUnit.SECONDS);
            return Result.success(new TokenVo(token,true));
        }
        //存在,直接签发token
        String token = token(member.getId());
        redisTemplate.opsForValue().set(token,token,3600,TimeUnit.SECONDS);
        return Result.success(new TokenVo(token,false));
    }

    @Override
    public Result info(ThMembers thMembers) {
        update(thMembers,null);
        return Result.success("更新信息成功");
    }



    public String token(String id){
        String token = JWT.create()
                .setPayload("id", id)
                .setKey(key.getBytes())
                .sign();
        log.info(token);
        return token;
    }


}
